<template>
  <div>
    <div class="list-area">
      <div class="setting-area glo-content-area">
        <div class="btns glo-btn-group">
             <!--  -->
          <!-- <Button
            type="primary"
            @click="handleupOffline"
          >{{$t('devicesIndex.devOfflineHint')}}</Button>

          <Button
            type="primary"
            @click="handleUpgradeaMulti"
          >{{ $t("devicesIndex.devUpgradeBtn") }}</Button>
          <Button
            type="primary"
            @click="handleBindAreaMulti"
          >{{ $t("devicesIndex.devBingBtn") }}</Button> -->
          <!-- 新增设备按钮 -->
          <Button
            type="primary"
            @click="showCreate"
            v-if="allPermissions.visitorsAdd"
          >{{$t('visitorsIndex.visitorsAdd')}}</Button>
        </div>
        <div class="title">{{$t('visitorsIndex.visitorsList')}}</div>
      </div>

      <div class="glo-search-area">
        <!-- <div class="widget-item">
          <div class="widget-label">访客类型：</div>
          <Select
            v-model="personType"
            placeholder="选择"

          >
            <Option
              v-for="(item, idx) in personTypes" :key="idx"
              :value="item.value"
            >{{ item.name }}</Option>
          </Select>
        </div> -->
        <div class="widget-item glo-clear-after">
          <div class="widget-label">{{$t('visitorsIndex.visitorsName')}}：</div>
          <Input
            v-model="name"
            :placeholder="$t('visitorsIndex.visitorsInputName')"
            search
            :enter-button="$t('devicesIndex.devNumberBtn')"
            @on-search="$_page_update"
          />
        </div>
        <div  class="widget-item glo-clear-after">
          <i-button style="margin-top: 36px;" type="primary"  @click="handleDel('DelAll')" v-if="allPermissions.stafferrorDel">{{ $t("staffIndex.stafferrorDel") }}</i-button>
        </div>
      </div>

      <div class="glo-selection">
        <Alert show-icon>
          {{ $t("devicesIndex.devSelected") }} {{ selection.length }} {{ $t("devicesIndex.devItem") }}
          <a class="glo-selection-clean" @click="handleSelectionAllStatus(false)">{{ $t("devicesIndex.devEmpty") }}</a>
        </Alert>
      </div>
      <Table
        ref="table"
        class="list"
        :data="list"
        :columns="columns"
        @on-selection-change="handleSelection"
      />
      <Page
        class="glo-content-area glo-pagenation"
        :total="total"
        :pageSize="pageSize"
        show-sizer
        :current="page"
        show-total
        @on-change="$_page_pageChange"
        @on-page-size-change="$_page_pageSizeChange"
      />
    </div>

    <Create
      v-if="ifCreate"
      @close="closeCreate"
    />
    <Create
      v-if="ifUpdate"
      edit-type="update"
      :edit-item="editItem"
      @close="closeUpdate"
    />
    
  </div>
</template>

<script>
import {
  getList,
  del,
  // bindArea,
  // upgrade,
  // restart,
  // open,
  // IDCard,
  // lineAccess,
  // openTime,
} from '@/api/visitors.js'
import pageMixin from '@/utils/mixins/pageMixin.js'
import {
  getPhoto,
} from '@/api/public.js'
import Create from './Create'
import ListSettings from './ListSettings'

export default {
  mixins: [
    pageMixin,
  ],
  components: {
    Create,
  },
  computed: {
    btnShow () {
      console.log(2222)
      return this.$store.state.btnShow
    },
  },

  watch: {
    
    btnShow(){
      this.columns = [
        { type: 'selection', width: 70 },
        {
          type: 'index',
          width: 60,
          indexMethod: this.$_index_method,
        },
        {
          title: this.$t('visitorsIndex.visitorsHead'),
          key: 'photo',
          width: 140,
          render: (h, { row }) => {
            if (!row.photo || row.photo === '') {
              return h('div', '-')
            }
            return h('div', {
              class: 'img-area',
            }, [

              h('Tooltip', {
                props: {
                  placement: 'right-start',
                  transfer: true,
                }
              }, [
                h('viewer', [
                  h('img', {
                    style: {
                      cursor: 'pointer',
                    },
                    attrs: {
                      src: getPhoto(row.photo),
                    },
                  }),
                ]), h('span', {
                  slot: 'content',
                  style: {
                    whiteSpace: 'normal',
                  }
                }, this.$t('title.clickBig')),

              ])
            ])
          },
        },
        {
          title: this.$t('visitorsIndex.visitorsNameTable'),
          key: 'realName',
        },
        {
          title: this.$t('visitorsIndex.visitorsPhone'),
          key: 'phone',
          render (h, { row }) {
            let label = '-'
            if (row.phone) {
              label = row.phone
            }
            return h('div', label)
          },
        },
        {
          title: this.$t('visitorsIndex.visitorsCardNum'),
          key: 'cardNum',
          render (h, { row }) {
            let label = '-'
            if (row.cardNum) {
              label = row.cardNum
            }
            return h('div', label)
          },
        },
        {
          title: this.$t('visitorsIndex.visitorsStartTime'),
          key: 'startTime',
          render: (h, { row }) => {
            let label = '-'
            if (row.startTime) {
              label = row.startTime
            }
            return h('div', label)
          },
        },
        {
          title: this.$t('visitorsIndex.visitorsEndTime'),
          key: 'endTime',
          render: (h, { row }) => {
            let label = '-'
            if (row.endTime) {
              label = row.endTime
            }
            return h('div', label)
          },
        },
        {
          title: this.$t('devicesIndex.devTableoperation'),
          key: 'settings',
          width: 200,
          render: (h, { row }) => {
            return h(ListSettings, {
              props: { row ,allPermissions:this.allPermissions},
              on: {
                itemClick: (name) => this.handleSettingsClick(name, row),
              },
            })
          },
        },
      ];

      return this.$store.state.btnShow
    }
  },

  data () {
    return {
      personTypes: [
        { name: this.$t('BodyTemperatureIndex.BodyTemAnimalStaff'), value: '1' },
        { name: this.$t('BodyTemperatureIndex.BodyTemAnimalStranger'), value: '0' },
      ],
      personType: '',
      sn: '',
      name: '',
      sex: 0,
      sexs: [
        { name: this.$t('devicesIndex.devOfflineAccessNo'), value: 0 },
        { name: this.$t('devicesIndex.devOfflineAccessYes'), value: 1 },
      ],
      modalSel: false,

      selection: [],
      list: [],
      columns: [
        { type: 'selection', width: 70 },
        {
          type: 'index',
          width: 60,
          indexMethod: this.$_index_method,
        },
        {
          title: this.$t('visitorsIndex.visitorsHead'),
          key: 'photo',
          width: 140,
          render: (h, { row }) => {
            if (!row.photo || row.photo === '') {
              return h('div', '-')
            }
            return h('div', {
              class: 'img-area',
            }, [

              h('Tooltip', {
                props: {
                  placement: 'right-start',
                  transfer: true,
                }
              }, [
                h('viewer', [
                  h('img', {
                    style: {
                      cursor: 'pointer',
                    },
                    attrs: {
                      src: getPhoto(row.photo),
                    },
                  }),
                ]), h('span', {
                  slot: 'content',
                  style: {
                    whiteSpace: 'normal',
                  }
                }, this.$t('title.clickBig')),

              ])
            ])
          },

        },
        {
          title: this.$t('visitorsIndex.visitorsNameTable'),
          key: 'realName',
        },
        {
          title: this.$t('visitorsIndex.visitorsPhone'),
          key: 'phone',
          render (h, { row }) {
            let label = '-'
            if (row.phone) {
              label = row.phone
            }
            return h('div', label)
          },
        },
        {
          title: this.$t('visitorsIndex.visitorsCardNum'),
          key: 'cardNum',
          render (h, { row }) {
            let label = '-'
            if (row.cardNum) {
              label = row.cardNum
            }
            return h('div', label)
          },
        },
        {
          title: this.$t('visitorsIndex.visitorsStartTime'),
          key: 'startTime',
          render: (h, { row }) => {
            let label = '-'
            if (row.startTime) {
              label = row.startTime
            }
            return h('div', label)
          },
        },
        {
          title: this.$t('visitorsIndex.visitorsEndTime'),
          key: 'endTime',
          render: (h, { row }) => {
            let label = '-'
            if (row.endTime) {
              label = row.endTime
            }
            return h('div', label)
          },
        },
        {
          title: this.$t('devicesIndex.devTableoperation'),
          key: 'settings',
          width: 200,
          render: (h, { row }) => {
            return h(ListSettings, {
              props: { row ,allPermissions:this.allPermissions},
              on: {
                itemClick: (name) => this.handleSettingsClick(name, row),
              },
            })
          },
        },
      ],

      ifCreate: false,
      ifUpdate: false,
      editItem: null,
      ifSelectArea: false,
      areaSelectCallback: null,
      allPermissions:{
        visitorsAdd:false,
        stafferrorDel:false,
        devListEdit:false,
        devListDel:false,
      },
    }
  },

  mounted () {
    this.$_page_update()
    this.getAllPermissions()
    // this.IDCard()
  },

  methods: {
    getAllPermissions(){
      let da=JSON.parse(window.localStorage.getItem('logo'))||[]
      da.map(v => {
        if(v.permission=='#visitors'&&v.children){
          v.children.map(a=>{
            if(a.permission=='#visitorsAdd'&&a.checked==='true'){
              this.allPermissions.visitorsAdd=true
            }
            if(a.permission=='#stafferrorDel3'&&a.checked==='true'){
              this.allPermissions.stafferrorDel=true
            }
            if(a.permission=='#devListEdit2'&&a.checked==='true'){
              this.allPermissions.devListEdit=true
            }
            if(a.permission=='#devListDel1'&&a.checked==='true'){
              this.allPermissions.devListDel=true
            }
            
          })
        }
      });
    },
    showCreate () {
      this.ifCreate = true
    },
    closeCreate (ifUpdated) {
      ifUpdated && this.$_page_update()
      this.ifCreate = false
    },

    showUpdate (item) {
      this.ifUpdate = true
      this.editItem = item
    },
    closeUpdate (ifUpdated) {
      ifUpdated && this.$_page_update()
      this.ifUpdate = false
    },

    showAreaSelect (cb) {
      this.areaSelectCallback = cb
      this.ifSelectArea = true
    },
    closeAreaSelect (ifUpdated) {
      ifUpdated && this.$_page_update()
      this.ifSelectArea = false
    },

    handleSelection (selection = []) {
      // console.log(selection)
      this.selection = selection
    },
    handleSelectionAllStatus (status) {
      this.$refs.table.selectAll(status)
    },
    handleBindAreaMulti () {
      const nowIds = this.selection
      if (nowIds.length === 0) {
        this.$Message.warning(this.$t('devicesIndex.devStrSel'))
        return
      }
      // 显示区域选择
      this.showAreaSelect(async (areaIdSel) => {
        const arr = nowIds.map(item => {
          return this.handleBind({
            deviceId: item.deviceId,
            areaId: areaIdSel,
            isBind: 1,
          })
        })
        await Promise.all(arr)
      })
    },
    handleBindArea (item) {
      const { areaId } = item
      if (!areaId) {
        // 显示区域选择
        this.showAreaSelect((areaIdSel) => {
          this.handleBind({
            deviceId: item.deviceId,
            areaId: areaIdSel,
            isBind: 1,
          })
        })
      } else {
        this.$Modal.confirm({
          title: this.$t('devicesIndex.devStrBindRemove'),
          content: this.$t('devicesIndex.devStrdelIsUre') + item.name + this.$t('devicesIndex.devStrdelIsNN'),
          onOk: async () => {
            this.handleBind({
              deviceId: item.deviceId,
              areaId,
              isBind: 0,
            })
          },
        })
      }
    },
    handleupOffline () {
      const nowIds = this.selection
      if (nowIds.length === 0) {
        this.$Message.warning(this.$t('devicesIndex.devOfflineAccessSel'))
        return
      }
      this.modalSel = true
    },
    okCenter () {
      this.modalSel = false
    },
    okSel () {
      var that = this
      that.selection.forEach((item, index) => {
        that.handleLineAccess({
          sn: item.sn,
          needPhoto: that.sex,
        })
      })
    },
    handleUpgradeaMulti () {
      const nowIds = this.selection
      if (nowIds.length === 0) {
        this.$Message.warning(this.$t('devicesIndex.devStrSelupgrade'))
        return
      }
      this.$Modal.confirm({
        title: this.$t('devicesIndex.devStrupgradeEquipment'),
        content: this.$t('devicesIndex.devStrupgradeEquipmentIs'),
        onOk: async () => {
          const arr = nowIds.map(item => {
            return this.handleUpgrade({
              sn: item.sn,
            })
          })
          await Promise.all(arr)
        },
      })
    },

    handleRestart (item) {
      this.$Modal.confirm({
        title: this.$t('devicesIndex.devStrRestart'),
        content: this.$t('devicesIndex.devStrRestartIsNew') + item.name + this.$t('devicesIndex.devStrDelEquipmentIsNNew'),
        onOk: async () => {
          const { success, data } = await restart({ sn: item.sn })
          if (success) {
            this.$Message.success(this.$t('devicesIndex.devStrRestarsUCC'))
            this.$_page_update()
          } else {
            this.$Message.error(data)
          }
        },
      })
    },

    handleOpen (item) {
      this.$Modal.confirm({
        title: this.$t('devicesIndex.devStrEquipmentName'),
        content: this.$t('devicesIndex.devStrEquipment') + item.name + this.$t('devicesIndex.devStrCutIs'),
        onOk: async () => {
          const { success, data } = await open({ sn: item.sn })
          if (success) {
            this.$Message.success(this.$t('devicesIndex.devStrCutSucc'))
            this.$_page_update()
          } else {
            this.$Message.error(data)
          }
        },
      })
    },
    handleTime (item) {
      this.$Modal.confirm({
        title: this.$t('devicesListSettings.devListTimeIs'),
        content: this.$t('devicesIndex.devStrEquipment') + item.name + this.$t('devicesListSettings.devListTimeIs'),
        onOk: async () => {
          const { success, data } = await openTime({ sn: item.sn })
          if (success) {
            this.$Message.success(this.$t('devicesListSettings.devListTimeSucc'))
            // this.$_page_update()
          } else {
            this.$Message.error(this.$t('devicesListSettings.devListTimeErr'))
          }
        },
      })
    },

    handleSettingsClick (name, row) {
      switch (name) {
        case 'edit':
          this.showUpdate(row)
          break
        case 'del':
          this.handleDel(row)
          break
        case 'bindArea':
          this.handleBindArea(row)
          break
        case 'restart':
          this.handleRestart(row)
          break
        case 'open':
          this.handleOpen(row)
          break
        case 'Time':
          this.handleTime(row)
          break
      }
    },

    async getData (query) {
      const { success, data } = await getList({
        page: query.page,
        limit: query.pageSize,
        realName: this.name,
      })
      let list = []
      let page = 1
      let total = 0
      if (success) {
        list = data.data
        page = data.pageNum || 1
        total = data.count
      }
      this.list = list
      this.page = page
      this.pageSize = query.pageSize
      this.total = total
      this.selection = []
    },
    async handleDel (item) {
      let delData=[];
      if(item=="DelAll"){
        if(!this.selection.length){
          this.$Message.error({
            content: this.$t('visitorsIndex.visitorsModalTitleHint2'),
            duration: 5,
          })
          return
        }
        this.selection.forEach((v ,i)=> {
          delData.push({mid:v.mid})
          // if(i!=this.selection.length-1){
          //   delData+=','
          // }
        });
      }else{
        console.log('删除一项')
        // delData= item.mid 
        delData.push({mid:item.mid})
      }
      this.$Modal.confirm({
        title: this.$t('visitorsIndex.visitorsModalTitle'),
        content: item=="DelAll"?this.$t('visitorsIndex.visitorsModalTitleHint1'):this.$t('visitorsIndex.visitorsModalTitleHint'),
        onOk: async () => {
          const { success } = await del(delData)
          // const { success } = await del({ ids: item.id })
          if (success) {
            this.$Message.success(this.$t('versionIndex.verDelBtnSucc'))
            this.$_page_update()
          } else {
            this.$Message.error(this.$t('versionIndex.verDelBtnF'))
          }
        },
      })
    },
    async handleBind (params) {
      const { success } = await bindArea(params)
      if (success) {
        this.$Message.success(this.$t('devicesIndex.devdevStrUpdateSucc'))
        this.$_page_update()
      } else {
        this.$Message.error(this.$t('devicesIndex.devdevStrUpdatefailed'))
      }
    },
    async handleUpgrade (params) {
      const { success, data } = await upgrade(params)
      if (success) {
        this.$Message.success(this.$t('devicesIndex.devdevStrupgradeSucc'))
        this.$_page_update()
      } else {
        this.$Message.error(this.$t('devicesIndex.devdevStrupgradeErr'))
      }
    },
    async handleLineAccess (params) {
      const { success, data } = await lineAccess(params)
      if (success) {
        this.$Message.success(this.$t('devicesIndex.devOfflineAccessSucc'))
        this.modalSel = false
        this.$_page_update()
      } else {
        this.$Message.error(this.$t('devicesIndex.devOfflineAccessErr'))
      }
    },

    
    async IDCard (params) {
      const { success, data } = await IDCard({
        'OP-DEV': 1,
        'CMD-URL': 14,
      })
      if (success) {
       
      } else {
        this.$Message.error(data)
      }
    },

  },
}
</script>

<style lang="less" scoped>
.setting-area {
  .clearfix();

  .btns {
    float: right;
  }
  .title {
    line-height: @lh-base;
    font-size: 18px;
    font-weight: bold;
  }
}
.list-area {
  overflow: hidden;

  /deep/ .img-area {
    width: 100px;
    height: 100px;
    margin: 6px 0;
    box-sizing: content-box;
    overflow: hidden;
    img {
      width: 100%;
    }
  }
}
</style>
